package com.oracle.cglib_proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class Cglib_Proxy {

    public static UserDaoImpl getCglibProxy(){

        //1.目标类
        UserDaoImpl userDaoImpl = new UserDaoImpl();

        //2.功能类
        MyAspect myAspect = new MyAspect();

        //3.代理类     Enhancer
        Enhancer enhancer = new Enhancer();

        //设置当前代理类的父类
        enhancer.setSuperclass(UserDaoImpl.class);

        //这个类帮我们创建一个 目标类的  子类
        // MethodInterceptor 方法拦截器，目的是在执行目标方法之前先
        //拦截， 拦截添加功能，然后在让你"走"
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

                myAspect.before();

                Object object = method.invoke(userDaoImpl, objects);

                myAspect.after();

                return object;
            }
        });
        //5. 创建目标类的子类
        UserDaoImpl o =(UserDaoImpl) enhancer.create();

        return  o;
    }









}
